package com.mes.web.controller.jy;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.mes.entity.hy.Equipment;
import com.mes.entity.jy.Dayshedu;
import com.mes.entity.jy.DaysheduDetail;
import com.mes.entity.jy.Plandetail;
import com.mes.entity.jy.Planjy;
import com.mes.entity.jy.Productroom;
import com.mes.entity.jy.Queryjy;
import com.mes.service.jy.CarRoomServise;
import com.mes.service.jy.DaysheduDetailServise;
import com.mes.service.jy.DaysheduServise;
import com.mes.service.jy.ProductPlanDetailServise;
import com.mes.service.jy.ProductPlanServise;
import com.mes.utils.ResponseUtil;

/**
 * @ClassName: DaysheduController 
 * @Description:生产排产
 * @Author jy
 * @Date 2017年12月29日 上午9:26:54 
 * @version 1.0
 */
@Controller
@RequestMapping("/jy")
public class DaysheduController {
	
	@Resource
	private CarRoomServise carRoomServise;
	@Resource
	private ProductPlanServise productPlanServise;
	@Resource
	private ProductPlanDetailServise productPlanDetailServise;
	@Resource
	private DaysheduServise daysheduServise;
	@Resource
	private DaysheduDetailServise daysheduDetailServise;

	/**
	 * 去排产单页面
	 * @return 排产页面
	 */
	@RequestMapping("goDayshedu")
	public String goDayshedu() {
		return "/jyy/dayshedu3";
	}
	
	/**
	 * 查询车间
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectCarroom")
	public void selectCarroom(HttpServletResponse response) throws Exception {
		//查询所有车间信息
		List<Productroom> list = carRoomServise.selectCarRoomAll();
		//转化成json
		Gson gson = new Gson();
		String json = gson.toJson(list);
		ResponseUtil.write(response, json);
	}
	
	/**
	 * 二级联动，根据车间查询设备
	 * @param cid 车间id
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectEquipment")
	public void selectEquipment(Long cid,HttpServletResponse response) throws Exception {
		//查询所有的设备（未删除的）
		List<Equipment> list = productPlanServise.selectEqupment2(cid);
		Gson gson = new Gson();
		String json = gson.toJson(list);
		ResponseUtil.write(response, json);
	}
	
	/**
	 * 查询可以排产的生产计划单
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectPlanCanShedu")
	public void selectPlanCanShedu(HttpServletResponse response) throws Exception{
		//所有未排产完的生产计划单
		Queryjy queryjy2= new Queryjy();
		//1.未关闭等， 2.未排产或未排产完成，3. 审批完成的
		List<Planjy> list= productPlanServise.selectProductPlanByState(queryjy2);
		 
		JSONObject jsonObject=new JSONObject();
		/*jsonObject.put("total", count);*/
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 去添加页面
	 * @param model 前端页面数据展示实体
	 * @return 返回添加排产页面
	 */
	@RequestMapping("/goCreatedayshedu")
	public String goCreatedayshedu (Model model) {
		//将计划单详情中的reartk 7,8,10清空
		productPlanDetailServise.editDyDetail2();
		//车间信息
		List<Productroom> list = carRoomServise.selectCarRoomAll();
		
		//所有未排产完的生产计划单
		Queryjy queryjy2= new Queryjy();
		//1.未关闭等， 2.未排产或未排产完成，3. 审批完成的
		List<Planjy> list2= productPlanServise.selectProductPlanByState(queryjy2);
		 
		//查询所有的设备（未删除的）
		Queryjy queryjy3= new Queryjy();
		List<Equipment> list3 = productPlanServise.selectEqupment(queryjy3);
		 
		model.addAttribute("list", list);
		model.addAttribute("list2", list2);
		model.addAttribute("list3", list3);
		return "jyy/createdayshedu";
	}
	
	/**
	 * 添加排产单
	 * @param dayshedu 排产实体
	 * @param request 请求
	 * @param response 响应
	 * @throws IOException 输入输出异常
	 */
	@RequestMapping("/createDayshedu")
	public void createDayshedu(Dayshedu dayshedu,HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		//添加前删除冗余数据
		/*daysheduDetailServise.deleteDaysheduNumNotin();*/
		
		int affact = 0;
		//添加前要先校验，1.此配货单信息是否已经添加过。2.在同一车间，同一设备，同一时间段是否已经添加过排产信息。
		int count = daysheduServise.selectDaysheduByDayshedunum(dayshedu.getDayshedunum());
		int count2 = daysheduServise.selectDaysheduByManay(dayshedu);
		if(count > 0) {
			//此排产单已存在
			affact = 2;
		}else if(count2 >0) {
			//同一车间，同一设备，同一班组，同一时间段，中已经排产
				affact = 3;
		}else {
			//获取系统时间，作为排产时间
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String format2 = format.format(date);
			dayshedu.setRemark(format2);
			dayshedu.setRemark1("未提交");
			affact = daysheduServise.createDayshedu(dayshedu);
			
			/*排产单保存成功后
			1:修改计划单详情中的未排产计划数量 并 修改详情中的状态
			先根据排产单号查询其所有详情，获取每条详情中的计划量，再根据计划详情id获取其未排产数量，减去排产中的数量*/
			List<DaysheduDetail> list2 = daysheduDetailServise.selectDaysheduDetailByDnum(dayshedu.getDayshedunum());
			if(list2 != null ) {
				for (DaysheduDetail daysheduDetail : list2) {
					if(daysheduDetail.getPlannum() != null && daysheduDetail.getPlannum() != "") {
						Integer plannum = Integer.valueOf(daysheduDetail.getPlannum());
						//对应计划详情id
						Long pdid = null;
						String remark5 = daysheduDetail.getRemark5();
						if(remark5 !=null ) {
							 pdid = Long.valueOf(remark5);
						}
						//再根据计划详情id获取其未排产数量
						Plandetail plandetail3= productPlanDetailServise.slectPlanDetailByid(pdid);
						//未排产数量
						Integer wpnum = Integer.valueOf(plandetail3.getRemartk11());
						if(wpnum > plannum) {
							Integer integer = wpnum-plannum;
							plandetail3.setRemartk11(integer.toString());
							plandetail3.setId(pdid);
							productPlanDetailServise.editRemark11(plandetail3);
							
							plandetail3.setWstape("排产中");
							productPlanDetailServise.editWstape(plandetail3);
							
							//将信息更新到对应的销售计划单中(根据销售计划详情id)
							plandetail3.setRemartk12("5");
							productPlanServise.editSstate2(plandetail3);
						}else {
							plandetail3.setId(pdid);
							plandetail3.setRemartk11(0+"");
							productPlanDetailServise.editRemark11(plandetail3);
							
							plandetail3.setWstape("已排产");
							productPlanDetailServise.editWstape(plandetail3);
							
							plandetail3.setRemartk12("2");
							//将信息更新到对应的销售计划单中(根据销售计划详情id)
							productPlanServise.editSstate2(plandetail3);
						}
					}//判断计划量是否为空
				}//判断排产单有没有对应的详情
			}
		}
		response.getWriter().print(affact);
	}
	
	/**
	 * 修改排产单
	 * @param dayshedu 排产实体
	 * @param request 请求
	 * @param response 响应
	 * @throws IOException 输入输出异常
	 */
	@RequestMapping("/editDayshedu")
	public void editDayshedu(Dayshedu dayshedu,HttpServletRequest request,HttpServletResponse response) throws IOException {
		int affact = 0;
		int count2 = daysheduServise.selectDaysheduByManay(dayshedu);
		if(count2 >1) {
			//同一车间，同一设备，同一班组，同一时间段，中已经排产
				affact = 3;
		}else {
			//获取系统时间，作为排产时间
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String format2 = format.format(date);
			dayshedu.setRemark(format2);
			affact = daysheduServise.editDayshedu(dayshedu);
		}
		response.getWriter().print(affact);
	}
	
	/**
	 * 带条件的分页查询日排产单
	 * @param request 请求
	 * @param queryjy 查询实体
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectDayshedu")
	public void selectDayshedu(HttpServletRequest request,Queryjy queryjy,HttpServletResponse response) throws Exception {
		
		//条件判空
		if(queryjy.getCarroom()!= null) {
			String carroom = queryjy.getCarroom();
			carroom = new String(carroom .getBytes("iso8859-1"),"utf-8");
			queryjy.setCarroom(carroom);
		}
		
		//统计排产单总数
		int count  = daysheduServise.countDayshedu(queryjy);
		//查询排产单集合
		List<Dayshedu> list = daysheduServise.selectDaysheduPagine(queryjy);
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 添加排产单详情
	 * @param daysheduDetail 排产单详情
	 * @param response 响应
	 * @throws IOException IO异常
	 * @throws ParseException Parse异常
	 */
	@RequestMapping("/createDaysheduDetail")
	public void createDaysheduDetail(DaysheduDetail daysheduDetail,HttpServletResponse response) throws IOException, ParseException {
		Integer moshu = Integer.valueOf(daysheduDetail.getRemark8());
		
		//一个小时3600秒
		Integer m = 3600;
		Integer fen = 60*moshu;
		//周期
		Integer cycle = Integer.valueOf(daysheduDetail.getCycle());
		//计划量
		Integer plannum = Integer.valueOf(daysheduDetail.getPlannum());
		
		//判断开始时间不为空时，根据开始时间计算结束时间
		String stattime = daysheduDetail.getStattime();
		if(stattime != null && stattime != "") {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
			Date parse = format.parse(stattime);
			//第一步：3600/周期=每小时生产量 72
			Integer hp = m/cycle;
			
			//第二步：计划量/每小时生产量 = 总共需要多少小时 13.8（精确到小时，具体的分钟数下边再另外计算）
			Integer h = plannum/(hp*moshu); 
			
			//第三步：要预留一个小时，开始时间+h+1 (13+1)
			String format2 = format.format(((parse.getTime()/1000)+60*60*(h+1))*1000); //22
			String endtime=String.valueOf(format2);
			daysheduDetail.setEndtime(endtime);
			//第四步：计算分钟
			Integer x = h*hp*moshu;//936
			
			Integer y = plannum-x;//64
			Double z =Double.valueOf(y*cycle);//3200
			Double ff = z/fen;//53
			int round =(int) Math.round(ff);
			
			//第五步，把分钟加上
			Date parse2 = format.parse(endtime);
			String format3 = format.format(((parse2.getTime()/1000)+60*round)*1000);
			daysheduDetail.setEndtime(format3);
		}
		
		//将信息更新到生产计划单详情中
		if(daysheduDetail.getRemark5() != null && daysheduDetail.getRemark5() != "") {
			Long id = Long.valueOf(daysheduDetail.getRemark5());//计划单详情id
			Plandetail plandetail = new Plandetail();
			plandetail.setId(id);
			plandetail.setRemartk7(daysheduDetail.getStattime());//排产开始时间
			plandetail.setRemartk8(daysheduDetail.getEndtime());//排产结束时间
			plandetail.setRemartk10(daysheduDetail.getPlannum());//排产计划量
			
			productPlanDetailServise.editDyDetail(plandetail);
			plandetail.setWstape("已排产");
		}
		daysheduDetail.setState("已排产");
		//添加排产单详情
		int affact = daysheduDetailServise.createDaysheduDetail(daysheduDetail);
		response.getWriter().print(affact);
	}
	
	/**
	 * 根据排产单号查询排产详情
	 * @param dayshedunum 排产单号
	 * @param equipment 设备
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectDaysheduDetail")
	public void selectDaysheduDetail(String dayshedunum,String equipment,HttpServletResponse response) throws Exception {
		
		//当前完成数量
		Integer num  = 0;
		//计划量
		Integer plnum = 0;
		//剩余数量
		Integer snum = 0;
		
		/*equipment = new String(equipment.getBytes("iso8859-1"),"utf-8");*/
		int count = daysheduDetailServise.countDaysheduDetail(dayshedunum);
		List<DaysheduDetail> list= daysheduDetailServise.selectDaysheduDetailByDnum(dayshedunum);
		
		for (DaysheduDetail daysheduDetail : list) {
			//根据排产详情id查询作业信息
	    	//当前完成数量、剩余数量(根据计划详情id查询)
			
			Long did= Long.valueOf(daysheduDetail.getId());
			//当前完成数量、剩余数量(根据计划详情id查询)
			String snum2 = productPlanServise.selectWorkBydid(did);
			if(snum2 != null && snum2 != "") {
				//实际量
	    		num = Integer.valueOf(snum2);
	    		//实际量
				daysheduDetail.setRemark7(num+"");
				//计划量
	    		plnum = Integer.valueOf(daysheduDetail.getPlannum());
	    		if(plnum != null) {
	    			if(num != null) {
	    				//剩余数量
	    				snum = plnum-num;
			    		daysheduDetail.setRemark2(snum+"");
	    			}
	    		}
	    	}else {
	    		//根据（remark1）
	    		String snum3 = productPlanServise.selectWorkBydid2(did);
    			if(snum3 != null && snum3 != "") {
    				//实际量
	    			 num = Integer.valueOf(snum3);
	    			//实际量
	 				daysheduDetail.setRemark7(num+"");
	 	    		//计划量
	 	    		plnum = Integer.valueOf(daysheduDetail.getPlannum());
	 	    		if(plnum != null) {
	 	    			if(num != null) {
	 	    				snum = plnum-num;
	 	    				//剩余数量
	 			    		daysheduDetail.setRemark2(snum+"");
	 	    			}
	 	    		}
				}
	    	}
    		num  = 0;
    		plnum = 0;
    		snum = 0;
		}
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 去编辑排产单页面
	 * @param id 排产单id
	 * @param model 前台页面需展示参数实体
	 * @return 编辑排产单页面
	 */
	@RequestMapping("/goEditdayshedu")
	public String goEditdayshedu(Long id,Model model) {
		//根据id查询排产单信息
		Dayshedu dayshedu= daysheduServise.selectDaysheduByid(id);
		//车间信息
		List<Productroom> list = carRoomServise.selectCarRoomAll();
		//查询所有的设备（未删除的）
		Queryjy queryjy3= new Queryjy();
		List<Equipment> list3 = productPlanServise.selectEqupment(queryjy3);
		 
		model.addAttribute("list", list);
		model.addAttribute("list3", list3);
		model.addAttribute("dayshedu", dayshedu);
		return "/jyy/editdayshedu";
	}
	
	/**
	 * 删除排产单(批量)
	 * @param ids 所有id字符串
	 * @param response 响应
	 * @throws IOException IO异常
	 */
	@RequestMapping("/deleteDayshedu")
	public void deleteDayshedu(String ids,HttpServletResponse response) throws IOException {
		
		//1.删除排产单
		 int affact = daysheduServise.deleteDayshedu(ids);
		 
		 //2.删除排产单中各详情
		 
		 //3.更改相对应的计划详情中的状态并把已排产数量加回待排产数量中。
		 
		 response.getWriter().print(affact);
	}
	
	
	/**
	 * 导出
	 * @param queryjy 条件查询实体类
	 * @param response 响应
	 * @throws UnsupportedEncodingException 异常
	 */
	@RequestMapping("/exportDayshedu")
	public void exportDayshedu(Queryjy queryjy,HttpServletResponse response) throws UnsupportedEncodingException {
		 // 第一步，创建一个webbook，对应一个Excel文件  
        HSSFWorkbook wb = new HSSFWorkbook();  
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet  
        HSSFSheet sheet = wb.createSheet("日排产单");  
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
        HSSFRow row = sheet.createRow((int) 0);  
        // 第四步，创建单元格，并设置值表头 设置表头居中  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
        
        HSSFCell cell = row.createCell(0);  
        cell.setCellValue("序号");  
        cell.setCellStyle(style);  
        cell = row.createCell(1);  
        cell.setCellValue("注塑机编号");  
        cell.setCellStyle(style);  
        cell = row.createCell(2);  
        cell.setCellValue("班次");  
        cell.setCellStyle(style);  
        cell = row.createCell(3);  
        cell.setCellValue("排产单号");  
        cell.setCellStyle(style);  
        cell = row.createCell(4);  
        cell.setCellValue("计划单号");  
        cell.setCellStyle(style);  
		
		 //根据条件查询数据库中所有的数据
        List<Dayshedu> list = daysheduServise.selectDaysheduPagine(queryjy);
	      for (int i = 0; i < list.size(); i++)
	        {
	            row = sheet.createRow((int) i + 1);
	            Dayshedu dayshedu= (Dayshedu) list.get(i);
	            // 第四步，创建单元格，并设置值
	            row.createCell(0).setCellValue((i+1));
	            row.createCell(1).setCellValue(dayshedu.getEquipment());
	            
	            if(dayshedu.getClazz() != null && dayshedu.getClazz() != "") {
	            	  if(dayshedu.getClazz() == "1") {
	  	            	row.createCell(2).setCellValue("白班");
	  	            }else {
	  	            	row.createCell(2).setCellValue("晚班");
	  	            }
	            }
	            row.createCell(3).setCellValue(dayshedu.getDayshedunum());
	            row.createCell(4).setCellValue(dayshedu.getPlannum());
	        }  
	        // 第六步，将文件存到指定位置  
	        Date now = new Date(); 
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//可以方便地修改日期格式 
		      String nowtime = dateFormat.format(now); 
	         
		      String fileName = "日排产单"+nowtime +".xls";
		      
		      fileName = new String(fileName.getBytes("GBK"),"iso8859-1"); 
	        try  
	        {
		        response.reset();   
		        response.setHeader("Content-Disposition","attachment;filename="+fileName);//指定下载的文件名   
		        response.setContentType("application/vnd.ms-excel");   
		        response.setHeader("Pragma", "no-cache");   
		        response.setHeader("Cache-Control", "no-cache");   
		        response.setDateHeader("Expires", 0);   
		        OutputStream output = response.getOutputStream();   
		        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);   
		        bufferedOutPut.flush();   
	            wb.write(bufferedOutPut);   
	            bufferedOutPut.close();   
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();  
	        } 
	}
	
	/**
	 * 根据排产单查询排产单详情列表
	 * @param dayshedunum 排产单编号
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectDaysheduDetailByNum")
	public void selectDaysheduDetailByNum(String dayshedunum,HttpServletResponse response) throws Exception {
		//查询排产详情集合
		List<DaysheduDetail> list = daysheduDetailServise.selectDaysheduDetailByDnum(dayshedunum);
		//查询排产详情总数
		int count = daysheduDetailServise.countDaysheduDetail(dayshedunum);
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 根据排产单详情关闭计划单详情
	 * @param dayshedudetail 排产单详情实体
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/shutdwonDayshedudetail")
	public void shutdwonDayshedudetail(DaysheduDetail dayshedudetail,HttpServletResponse response) throws Exception {
		int affact = 0;
		//根据id修改生产计划单的完成状态 为关闭
		dayshedudetail.setState("关闭");
		affact= daysheduDetailServise.editWstape(dayshedudetail) ;
		ResponseUtil.write(response, affact);
	}
	
	/**
	 * 作业信息页面根据设备和时间查询排产单详情
	 * @param queryjy 条件查询实体
	 * @param machin 设备
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/selectDysheduDetailByAllw")
	public void selectDysheduDetailByAllw(Queryjy queryjy, String machin,HttpServletResponse response) throws Exception {
		
		queryjy.setMachin(machin);
		//统计总数
		int count = daysheduDetailServise.countDysheduDetailByAllw(queryjy);
		//查询实体集合
		List<DaysheduDetail> list = daysheduDetailServise.selectDysheduDetailByAllw(queryjy);
		
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("total", count);
		jsonObject.put("rows", list);
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 发起生产计划申请，修改计划单
	 * @param ids 所有被选中的id组成的字符串
	 * @param response 响应
	 * @param request 请求
	 * @throws IOException IO异常
	 */
	@RequestMapping("/startApply2")
	public void startApply(String ids,HttpServletResponse response,HttpServletRequest request) throws IOException{
		String[] split = ids.split(",");
		for (String s : split) {
			Long id = Long.valueOf(s);
			
			//修改审核状态
			Dayshedu dayshedu = new Dayshedu();

			//修改审核状态
			dayshedu.setRemark1("审批完成");
			dayshedu.setRemark2("");
			dayshedu.setId(id);
			//根据id修改审批状态，以及审批流程id
			daysheduServise.editDaySheduState(dayshedu);
		}
		response.getWriter().print(1);
	}
	
	/**
	 * 校验添加排产单时是否有详情
	 * @param dayshedunum 排产单单号
	 * @param response 响应
	 * @throws IOException 异常
	 */
	@RequestMapping("selectDaysheduDetail2")
	public void selectDaysheduDetail2(String dayshedunum,HttpServletResponse response) throws IOException {
		//排产详情集合
		List<DaysheduDetail> list = daysheduDetailServise.selectDaysheduDetailByDnum2(dayshedunum);
		if(list.size() > 0) {
			//有
			response.getWriter().print(1);
		}else {
			//没有
			response.getWriter().print(0);
		}
	}
	
}
